package com.aaa.ws.controller;

import com.aaa.common.util.JwtUtils;
import com.aaa.common.util.SmsUtil;
import com.aaa.ws.entity.User;
import com.aaa.ws.service.UserService;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.aaa.common.util.BaseController;
import com.aaa.common.util.Result;
import com.aaa.common.vo.Page;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-07-03 10:36:55
 */
@RestController
@RequestMapping("userA")
public class UserController extends BaseController {

    //依赖注入  spring框架封装的Redis连接模板类
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 服务对象
     */
    @Resource
    private UserService userService;


    @Resource
    private HttpServletRequest request;

    /**
     * 验证登录
     *
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestParam("phone") String phone, @RequestParam("password") String password) {
        System.out.println("phone-----"+phone);
        System.out.println("password-----"+password);
        return this.userService.login(phone, password);
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    @GetMapping("checkToken")
    public boolean checkToken(@RequestParam("token") String token) {
        //调用服务层验证
        return userService.checkToken(token);
    }
    /**
     * 前端token查询 ------------
     * @return
     */
    @GetMapping("queryUserA")
    public Result queryUserA() {
        //public Result queryUserA(String token) {

        String token = request.getHeader("token");
        System.out.println("queryUserA-->token--->"+token);


        String tokenSub = token.substring(token.indexOf("-") + 1);

        Map<String, Claim> payloadByToken = JwtUtils.getPayloadByToken(tokenSub);
        Claim userId1 = payloadByToken.get("userId");
        System.out.println(userId1+".................");
        //userId="1"
        String userId = userId1.toString().replace("\"", "");



        //return success(userService.queryById(Integer.valueOf(userId)));
        return queryById(Integer.valueOf(userId));

    }

    /**
     * 根据手机号查询
     *
     * @param phone
     * @return
     */
    @PostMapping("checkNum")
    public Result checkNum(@RequestParam("phone") String phone) {
        Result result = success(userService.checkNum(phone));
        System.out.println("执行了查询手机号操作" + phone + "-------" + result);

        if (result != null) {
            return result;
        }
        return null;

    }

    /**
     * 生成验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("createCode")
    public Result createCode(@RequestParam("phone") String phone) {
        //生成随机验证码
        Random random = new Random();
        String num = (random.nextInt(900000) + 100000) + "";
        //生成验证码session
        System.out.println(num + "--------------------------------------------------------------------");
        System.out.println(phone + "+++++++++++++++++++++++++++++++++++++++++++++++++++");
        //调用工具类中发送信息方法  需要参数手机号和验证码
        String isSuc = SmsUtil.SendSms(phone, num);

        System.out.println(isSuc + "--isSuc--------------");

        //jedis.setex(mobile, 600, num);

        //还要把生成的isSuc存储到redis中 方便后面用来校验isSuc随机验证码
        //设置redis的key的序列化方式  使用StringRedisSerializer方式时，存储的redis中的就是string字符串
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //将验证码存入到redis中300秒后过期
        redisTemplate.opsForValue().set(phone, num, 600000000, TimeUnit.MILLISECONDS);

        //如果验证码生成成功 返回success
        if (isSuc.equals("error") || isSuc == null || isSuc == "") {
            System.out.println();
            return error("500");
        }

        System.out.println();
        return success("200");
    }


    /**
     * 判断验证码是否正确
     *
     * @param sms
     * @return
     */
    @PostMapping("checkSms")
    public Result checkSms(@RequestParam("sms") String sms, @RequestParam("phone") String phone) {

        //设置redis的key的序列化方式 使用StringRedisSerializer方式时 存储的redis中就是String字符串
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        System.out.println("输入的验证码为：" + sms);

        if (redisTemplate.hasKey(phone)) {
            System.out.println(sms + "================");
            //从redis中的获取的验证码
            String RedisSms = redisTemplate.opsForValue().get(phone).toString();
            System.out.println("RedisSms取出的验证码------" + RedisSms);
            //
            if (RedisSms.equals(sms)) {
                System.out.println();
                return success("200");

            } else {
                return error("500");
            }
        } else {
            return error("500");
        }
    }





    /**
     * 分页查询
     *
     * @param page 分页查询封装
     * @return 查询结果
     */
    @PostMapping("queryByPage")
    public Result queryByPage(@RequestBody Page<User> page) {
        return success(this.userService.queryByPage(page));
    }

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("queryById")
    public Result queryById(Integer id) {
        return success(this.userService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody User user) {
        return success(this.userService.insert(user));
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PutMapping("edit")
    public Result edit(@RequestBody User user) {
        return success(this.userService.update(user));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("deleteById")
    public Result deleteById(Integer id) {
        return success(this.userService.deleteById(id));
    }

}

